package com.countertack.dynamicinstrumentation;

import java.io.File;
import java.io.FileOutputStream;

import com.countertack.ssh.SSHManager;
import com.countertack.utils.Configuration;
import com.countertack.utils.CustomFileFilter;
import com.countertack.utils.Utils;
import com.countertack.vmware.VMWareConnector;
import com.vmware.vim25.mo.VirtualMachine;

public class CreateSnapShots {

	public static void main(String[] args) throws Exception {

		if (args.length <= 0) {

			System.out.println("configuration details missed !");
			return;
		}
		String configFilePath = args[0];
		long stTime = System.currentTimeMillis();
		// String configFilePath = "config.properties";
		// "C:\\Users\\user\\Desktop\\configm.properties";
		StringBuffer symbolsBuffer = new StringBuffer();
		Configuration.loadProperties(configFilePath);
		String rootSnapShotName = Configuration.getProperty("rootsnapshotname");
		String kbFilesLocation = Configuration.getProperty("kbfilespath");
		String vmUser = Configuration.getProperty("vmuser");
		String vmPassword = Configuration.getProperty("vmpassword");
		String[] kbsets = Configuration.getProperty("kbsets").split(",");
		// connect to esxi and starting virtual machines
		VMWareConnector esxiConnector = new VMWareConnector(
				Configuration.getProperty("esxi"));
		VirtualMachine vm = esxiConnector.getVirtualMachineByname(Configuration
				.getProperty("vmname"));

		String endpointMachineStatus = esxiConnector
				.getVirtualMachineStatus(vm);

		if (endpointMachineStatus == null) {

			System.out.println("Power on  endpoint machine .....");

			esxiConnector.startVirtualMachine(vm);

			Thread.sleep(600000);

		} else {

			if ("notRunning".equalsIgnoreCase(endpointMachineStatus)) {

				esxiConnector.reStartVirtualMachine(vm);

				System.out.println("Rebooting endpoint machine .....");

				Thread.sleep(600000);

			}

		}

		String vmIp = Configuration.getProperty("vmip");

		if (vmIp == null) {

			vmIp = vm.getGuest().ipAddress;

		}
		System.out.println("VM Ip Address>>>" + vmIp);
		esxiConnector.revertToSnapShort(vm.getSnapshot().getRootSnapshotList(),
				rootSnapShotName);

		System.out.println("Reverting to root snap shot>>>>>"
				+ rootSnapShotName);

		Thread.sleep(120000);

		for (String kbSet : kbsets) {
			try{
				esxiConnector.closeEsxiConnection();
				esxiConnector=new VMWareConnector(Configuration.getProperty("esxi"));
				
				vm = esxiConnector.getVirtualMachineByname(Configuration
						.getProperty("vmname"));
			}catch(Exception e){
				
				
				
				
			}

			endpointMachineStatus = esxiConnector.getVirtualMachineStatus(vm);

			if (endpointMachineStatus == null) {

				System.out.println("Power on  endpoint machine .....");

				esxiConnector.startVirtualMachine(vm);

				Thread.sleep(600000);

			} else {

				if ("notRunning".equalsIgnoreCase(endpointMachineStatus)) {

					esxiConnector.reStartVirtualMachine(vm);

					System.out.println("Rebooting endpoint machine .....");

					Thread.sleep(600000);

				}

			}

			String[] tcp_ntos = kbSet.split("_");
			String tcpIp = kbFilesLocation + "\\" + tcp_ntos[0];
			String ntos = kbFilesLocation + "\\" + tcp_ntos[1];

			File tcpIpRoot = new File(tcpIp);
			File ntosRoot = new File(ntos);

			if (tcpIpRoot.exists()) {

				File[] cabFiles = tcpIpRoot.listFiles(new CustomFileFilter(
						".cab"));
				if (cabFiles.length <= 0) {
					File[] msiFiles = tcpIpRoot.listFiles(new CustomFileFilter(
							".msu"));
					if (msiFiles.length <= 0) {

						File[] exeFiles = tcpIpRoot
								.listFiles(new CustomFileFilter(".exe"));
						tcpIp = tcpIp + "\\" + exeFiles[0].getName();

					} else {

						tcpIp = tcpIp + "\\" + msiFiles[0].getName();

					}
				} else {

					tcpIp = tcpIp + "\\" + cabFiles[0].getName();

				}

			}

			if (ntosRoot.exists()) {
				File[] cabFiles = ntosRoot.listFiles(new CustomFileFilter(
						".cab"));
				if (cabFiles.length <= 0) {
					File[] msiFiles = ntosRoot.listFiles(new CustomFileFilter(
							".msu"));
					if (msiFiles.length <= 0) {

						File[] exeFiles = ntosRoot
								.listFiles(new CustomFileFilter(".exe"));
						ntos = ntos + "\\" + exeFiles[0].getName();

					} else {

						ntos = ntos + "\\" + msiFiles[0].getName();

					}
				} else {

					ntos = ntos + "\\" + cabFiles[0].getName();

				}

			}
			SSHManager vmSsh = new SSHManager(vmUser, vmPassword, vmIp);
			vmSsh.connect();

			Utils.installKBonVirtualMachine(vmSsh,
					new String[] { tcpIp, ntos }, vm,
					esxiConnector.getOperationManager());

			vmSsh.doReconnect = false;
			vmSsh.closeSession();
			esxiConnector.reStartVirtualMachine(vm);
			System.out.println("Restarting VM");
			Thread.sleep(360000);
			if ("Running".equalsIgnoreCase(esxiConnector
					.getVirtualMachineStatus(vm))) {
				// gathering symbols
				vmSsh = new SSHManager(vmUser, vmPassword, vmIp);
				vmSsh.connect();

				String tcpIpsymchk = vmSsh
						.returnCommandOutPut("cmd /c cd \"C:\\Program Files\\"
								+ Configuration.getProperty("debugtoolname")
								+ "\" && symchk /v \"c:\\windows\\system32\\drivers\\tcpip.sys\"");

				if (tcpIpsymchk != null) {

					if (tcpIpsymchk.indexOf("C:\\Windows\\SYMBOLS\\tcpip.pdb") != -1) {

						tcpIpsymchk = tcpIpsymchk.substring(tcpIpsymchk
								.indexOf("C:\\Windows\\SYMBOLS\\tcpip.pdb")
								+ "C:\\Windows\\SYMBOLS\\tcpip.pdb".length());
						if (tcpIpsymchk.indexOf("tcpip.pdb") != -1) {

							tcpIpsymchk = tcpIpsymchk.substring(0,
									tcpIpsymchk.indexOf("tcpip.pdb"));

						}

					}

				}

				String ntosSymchk = vmSsh
						.returnCommandOutPut("cmd /c cd \"C:\\Program Files\\"
								+ Configuration.getProperty("debugtoolname")
								+ "\" && symchk /v \"c:\\windows\\system32\\ntoskrnl.exe\"");

				if (ntosSymchk != null) {
					// C:\Windows\SYMBOLS\ntkrnlmp.pdb\
					if (ntosSymchk
							.indexOf("C:\\Windows\\SYMBOLS\\ntkrnlmp.pdb") != -1) {

						ntosSymchk = ntosSymchk
								.substring(ntosSymchk
										.indexOf("C:\\Windows\\SYMBOLS\\ntkrnlmp.pdb")
										+ "C:\\Windows\\SYMBOLS\\ntkrnlmp.pdb"
												.length());
						if (ntosSymchk.indexOf("ntkrnlmp.pdb") != -1) {

							ntosSymchk = ntosSymchk.substring(0,
									ntosSymchk.indexOf("ntkrnlmp.pdb"));

						}

					}

				}

				String snapShotName = "TCPIP" + tcp_ntos[0] + "_NTOSKRNL"
						+ tcp_ntos[1];
				symbolsBuffer.append(snapShotName + ":" + tcpIpsymchk + "__"
						+ ntosSymchk + "\n");
				// creating snapshot

				esxiConnector.createSnapShot(vm, snapShotName, snapShotName);
				Thread.sleep(120000);

				// reverting to root snap shot

				esxiConnector.revertToSnapShort(vm.getSnapshot()
						.getRootSnapshotList(), rootSnapShotName);
				Thread.sleep(120000);

			}
			addResultsToLog(symbolsBuffer);

		}

		// VMWareConnector esxiConnector = new VMWareConnector("10.140.63.49");
		//
		// final VirtualMachine endPointMachine = esxiConnector
		// .getVirtualMachineByname("win7x64-sym-2");
		//
		// esxiConnector.revertToSnapShort(endPointMachine.getSnapshot()
		// .getRootSnapshotList(), "KB2868623_KB2709715");

		System.out.println("Snapshots creation is completed");
		System.out.println("Total time taken>>>"
				+ (System.currentTimeMillis() - stTime));

	}

	public static void addResultsToLog(StringBuffer vals) {
		File testCaseResFile = new File("Di_symbols_"
				+ Configuration.getProperty("vmname") + ".txt");

		try {
			testCaseResFile.createNewFile();
			FileOutputStream fout = new FileOutputStream(testCaseResFile);

			//

			fout.write(vals.toString().getBytes());

			fout.flush();
			fout.close();

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

}
